# -*- coding;utf-8 -*-
"""
File name : ZipOperate.py.PY
Program IDE : PyCharm
Create file time: 2025/6/11 13:50
File Create By Author : 朱清闯
"""

import os
import zipfile


def compress_folder_zip(folder_to_compress):
    """
    将指定文件夹下的所有内容压缩成a.zip并保存到该文件夹下

    参数:
        folder_to_compress (str): 需要压缩的文件夹路径

    返回:
        str: 压缩后的zip文件路径，失败时返回None
    """
    # 检查文件夹是否存在
    if not os.path.exists(folder_to_compress) or not os.path.isdir(folder_to_compress):
        print(f"错误：'{folder_to_compress}' 不是有效的文件夹路径")
        return None

    # 指定压缩文件的保存路径
    output_zip = os.path.join(folder_to_compress, 'a.zip')

    # 创建压缩文件
    try:
        with zipfile.ZipFile(output_zip, 'w', zipfile.ZIP_DEFLATED) as zipf:
            # 遍历文件夹中的所有文件
            for root, dirs, files in os.walk(folder_to_compress):
                for file in files:
                    # 跳过目标压缩文件本身（避免将a.zip也压缩进去）
                    file_path = os.path.join(root, file)
                    if file_path == output_zip:
                        continue

                    # 计算在zip文件中的相对路径
                    arcname = os.path.relpath(file_path, folder_to_compress)
                    zipf.write(file_path, arcname)
                    print(f"已添加: {arcname}")

        print(f"压缩完成！文件已保存至: {output_zip}")
        return output_zip

    except Exception as e:
        print(f"压缩过程中出错: {e}")
        return 'error'


def zip_folder(from_folder, to_folder):
    """使用zipfile模块的替代实现"""
    from_folder = os.path.abspath(from_folder)
    to_folder = os.path.abspath(to_folder)

    if not os.path.exists(to_folder):
        os.makedirs(to_folder)

    folder_name = os.path.basename(from_folder)
    zip_file_path = os.path.join(to_folder, f"{folder_name}.zip")

    try:
        with zipfile.ZipFile(zip_file_path, 'w', zipfile.ZIP_DEFLATED) as zipf:
            for root, dirs, files in os.walk(from_folder):
                # 计算当前文件在ZIP中的相对路径
                for file in files:
                    file_path = os.path.join(root, file)
                    # 获取相对路径，避免将完整的绝对路径添加到ZIP中
                    arcname = os.path.relpath(file_path, from_folder)
                    zipf.write(file_path, arcname)
            return zip_file_path
    except Exception as e:
        print(f"压缩过程中发生错误: {e}")
        return None


# 示例使用
if __name__ == "__main__":
    # 替换为你需要压缩的文件夹路径
    folder_path = "images"
    compress_folder_zip(folder_path)
